   //
//  InputListBaseViewController.m
//  RomensUISDK
//
//  Created by 裴飞杨 on 2018/4/18.
//  Copyright © 2018年 Romens. All rights reserved.
//

#import "InputListBaseViewController.h"
#import <RomensSDK/MBProgressHUD.h>
#import "InputReloadView.h"
#import "ShowDetailView.h"

@interface InputListBaseViewController () {
    NSString *_oldInputValues;       /*请求下来的输入信息*/
}
//重新加载View
@property (nonatomic,strong) InputReloadView *reloadView;
//展示数据View
@property (nonatomic,strong) ShowDetailView *showDetaiView;
@property (nonatomic, strong) MBProgressHUD *hudView;
@end

@implementation InputListBaseViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self creatInputUI];
    [self initLoadView];
    [self handleListData];
    [self fetchListData];
    [self creatReloadView];
}
-(void)dealloc {
    self.viewModel = nil;
    NSLog(@"释放了......");
}
#pragma mark - 过场动画
-(void)initLoadView {
    if (!self.hiddenHud) {
        [self.view addSubview:self.hudView];
        [self showHudView:@"正在同步数据"];
    }
}
#pragma mark - 会员档案UI
-(void)creatInputUI {
    [self.view addSubview:self.mainView];
    
    NSDictionary *views = NSDictionaryOfVariableBindings(_mainView);
    [self.view addConstraints:[ToolHelper GetNSLayoutCont:views format:@"H:|[_mainView]|"]];
    [self.view addConstraints:[ToolHelper GetNSLayoutCont:views format:@"V:|[_mainView]|"]];
}
#pragma mark - 重新加载View
-(void)creatReloadView {
    [self.view addSubview:self.reloadView];
    NSDictionary *views = NSDictionaryOfVariableBindings(_reloadView);
    [self.view addConstraints:[ToolHelper GetNSLayoutCont:views format:@"H:|-10-[_reloadView]-10-|"]];
    [self.view addConstraint:[NSLayoutConstraint constraintWithItem:_reloadView
                                                          attribute:NSLayoutAttributeCenterX
                                                          relatedBy:NSLayoutRelationEqual
                                                             toItem:self.mainView
                                                          attribute:NSLayoutAttributeCenterX
                                                         multiplier:1.0
                                                           constant:0.0]];
    [self.view addConstraint:[NSLayoutConstraint constraintWithItem:_reloadView
                                                          attribute:NSLayoutAttributeCenterY
                                                          relatedBy:NSLayoutRelationEqual
                                                             toItem:self.mainView
                                                          attribute:NSLayoutAttributeCenterY
                                                         multiplier:1.0
                                                           constant:0.0]];
}
//子类重写的方法
-(void)fetchListData {}
-(NSString *)setupSaveInputDataUrl{return @"";}

#pragma mark - 获取模板数据
-(void)handleListData {
    __weak typeof(self)weakSelf = self;
    self.inputReturnDataBlock = ^(InputDataModel *returnValue) {
        [weakSelf hiddenHudView];
        NSString *modelTypeStr = returnValue.modelType;
        if ([modelTypeStr isEqualToString:DataModelType1]) {
            weakSelf.viewModel.dataModel = returnValue;
            
        } else if ([modelTypeStr isEqualToString:DataModelType2]) {
            if (returnValue.dataModels.count > 0) {
                weakSelf.viewModel.dataModel = returnValue.dataModels[0];
                weakSelf.viewModel.dataModel.editInput = returnValue.editInput;
            }
        }
        if (weakSelf.viewModel.dataModel.templates.count == 0) {
            return;
        }
        weakSelf.mainView.viewModel = weakSelf.viewModel;
        [weakSelf saveInputDefaultValue];
        [weakSelf requestFunctionMenu];
    };
    self.inputReturnErrorBlock = ^(NSString *error) {
        [weakSelf hiddenHudView];
        if (!isEmptyString(error)) {
            weakSelf.reloadView.reloadLabel.text = [NSString stringWithFormat:@"%@", error];
            weakSelf.reloadView.hidden = NO;
        }
    };
}

-(void)requestFunctionMenu {
    [self creatNavigationItemRightBarBtn];
}

#pragma mark - 创建导航栏按钮
-(void)creatNavigationItemRightBarBtn {
    if (self.navigaRightBarItemType == NavigationRightBarItemNone) {
        return;
    }
    if (!self.viewModel.dataModel.editInput) {
        //创建编辑按钮
        [self creatEditBtn];
    } else {
        //创建完成按钮
        [self creatInputDoneBtn];
    }
}
-(void)creatEditBtn {
    UIBarButtonItem *editBtn = [[UIBarButtonItem alloc]
                                initWithTitle:@"编辑" style:UIBarButtonItemStylePlain
                                target:self
                                action:@selector(editInput)];
    self.navigationItem.rightBarButtonItem = editBtn;
}
//rightBarButtonItem
-(void)creatInputDoneBtn {
    UIBarButtonItem *doneBtn = [[UIBarButtonItem alloc]
                                initWithTitle:@"完成" style:UIBarButtonItemStylePlain
                                target:self
                                action:@selector(updateInputNodesByServer)];
    self.navigationItem.rightBarButtonItem = doneBtn;
}

#pragma mark - 保存数据
-(void)updateInputNodesByServer {
    if (!self.viewModel || !self.viewModel.dataModel.templates || self.viewModel.dataModel.templates.count == 0) {
        [self showHint:@"修改失败，缺少本地参数" yOffset:HINTOFF];
        return;
    }
    if ([self judgeNodesIsMustInput]) {
        return;
    }
    [self showHud:@""];
    __block bool requestSuccess = false;
    __block NSString *successDataJson = @"";
    __block NSString *errorMsg = @"";
    dispatch_group_t group = dispatch_group_create();
    __weak typeof(self)wSelf = self;
    for (InputSectionModel *sectionModel in self.viewModel.dataModel.templates) {
        dispatch_group_enter(group);
        NSMutableDictionary *parames = [self spliceInputDoneParames:sectionModel];
        [self requestSaveInputDataWithQueryType:sectionModel.updateFunc parames:parames block:^(id respone) {
            [wSelf HiddenHud];
            dispatch_group_leave(group);
            WebRequestData *data = (WebRequestData *)respone;
            if (!isEmptyString(data.Error) || isEmptyString(data.RequestData)) {
                errorMsg = isEmptyString(data.Error)? @"保存失败，原因：返回值为空": data.Error;
                return;
            }
            id dataObj = [ToolHelper JsonToDictionary:data.RequestData];
            if ([dataObj isKindOfClass:[NSDictionary class]]) {
                NSDictionary *dataDict = (NSDictionary *)dataObj;
                if ([dataDict[@"DATA"] isEqualToString:@"1"]) {
                    successDataJson = data.RequestData;
                    requestSuccess = YES;
                } else {
                    errorMsg = @"保存失败,原因:保存格式出错";
                }
            } else {
                errorMsg = @"保存失败,原因:保存格式出错";
            }
        }];
    }
    dispatch_group_notify(group, dispatch_get_main_queue(), ^{
        if (requestSuccess) {
            [wSelf saveSuccess:successDataJson];
        } else {
            [wSelf showHint:errorMsg yOffset:HINTOFF];
        }
    });
}
//判断必填项,有必填项且为空返回YES
-(BOOL)judgeNodesIsMustInput {
    return [self.viewModel isMustInput];
}
//拼接保存的参数
-(NSMutableDictionary *)spliceInputDoneParames:(InputSectionModel *)sectionModel {
    NSMutableDictionary *dic = [[NSMutableDictionary alloc] init];
    //拼接录入的数据
    NSMutableDictionary *data = [[NSMutableDictionary alloc] init];
    NSMutableDictionary *values = [self inputValuesWithNodes:sectionModel.nodes];
    [data setObject:values forKey:@"values"];
    [data setValue:@"0" forKey:@"state"];
    [dic  setObject:data forKey:@"DATA"];
    
    //拼接服务器返回的参数
    for (NSString *param in sectionModel.updateParamsArray) {
        NSString *paramStr = @"";
        if (sectionModel.dataDic) {
            paramStr = [ToolHelper isEmptyStr:sectionModel.dataDic[param]];
        }
        [dic setObject:paramStr forKey:param];
    }
    //拼接本地参数
    [dic setValue:sectionModel.codeKey forKey:@"TEMPLATECODE"];
    return dic;
}

//获取输入的每条数据
-(NSMutableDictionary *)inputValuesWithNodes:(NSMutableArray *)nodes {
    NSMutableDictionary *values = [[NSMutableDictionary alloc] init];
    for (InputCellModel *cellModel in nodes) {
        NSString *detailStr = [InputToolHelperClass selectNodeInputValue:cellModel];
        NSString *keyStr = [ToolHelper isEmptyStr:cellModel.codeKey];
        if (!isEmptyString(keyStr)) {
            [values setValue:detailStr forKey:keyStr];
        }
    }
    return values;
}

//保存方法
-(void)requestSaveInputDataWithQueryType:(NSString *)queryType parames:(NSMutableDictionary *)paramrs block:(void(^)(id respone))block {
    NSString *url = [self setupSaveInputDataUrl];
    if (isEmptyString(url)) {
        WebRequestData *data = [[WebRequestData alloc] init];
        data.Error = @"保存失败，请设置保存方法URL";
        block(data);
        return;
    }
    [self Request:url queryType:queryType postData:paramrs success:^(id respone) {
        block(respone);
    }];
}

//更新SectionModel中Nodes中的值
-(void)updateTemplteNodesValue:(InputSectionModel *)sectionModel withKeyValues:(NSDictionary *)dict {
    for (InputCellModel *cellModel in sectionModel.nodes) {
        for (NSString *key in dict.allKeys) {
            if ([cellModel.codeKey isEqualToString:key]) {
                cellModel.inputDetail = [ToolHelper isEmptyStr:dict[key]];
            }
        }
    }
}

//返回前一页
-(void)saveSuccess:(NSString *)dataJson {
    [self.navigationController popViewControllerAnimated:YES];
}
#pragma mark - 点击编辑
-(void)editInput {
    [self.viewModel editInput];
    [self creatInputDoneBtn];
}

#pragma mark - 重新加载
-(void)reloadRequest {
    self.reloadView.hidden = YES;
    [self fetchListData];
    [self initLoadView];
}

#pragma mark -查看详情
-(void)showDetailView:(NSString *)title value:(NSString *)value {
    self.showDetaiView.titleStr = title;
    self.showDetaiView.valueStr = value;
    [self.showDetaiView showContactView];
}
#pragma mark - 点击返回判断是否已经修改
- (BOOL)navigationShouldPopOnBackButton {
    if ([self updateInputVaulesByLocal]) {
        [self creatAlertView];
        return NO;
    } else {
        return YES;
    }
}
#pragma mark - 提示是否保存
-(void)creatAlertView {
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:nil message:@"是否保存已修改的信息" preferredStyle:UIAlertControllerStyleAlert];
    NSMutableAttributedString *titleAttributed = [[NSMutableAttributedString alloc] initWithString:@"是否保存已修改的信息"];
    [titleAttributed addAttribute:NSFontAttributeName value:systemDefaultFont range:NSMakeRange(0, [[titleAttributed string] length])];
    [titleAttributed addAttribute:NSForegroundColorAttributeName value:[UIColor blackColor] range:NSMakeRange(0, [[titleAttributed string] length])];
    [alert setValue:titleAttributed forKey:@"attributedMessage"];
    
    UIAlertAction *okAction = [UIAlertAction actionWithTitle:@"保存" style:   UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [self updateInputNodesByServer];
    }];
    UIAlertAction *popAction = [UIAlertAction actionWithTitle:@"不保存" style:UIAlertActionStyleDestructive handler:^(UIAlertAction * _Nonnull action) {
        [self.navigationController popViewControllerAnimated:YES];
    }];
    [alert addAction:okAction];
    [alert addAction:popAction];
    [self presentViewController:alert animated:YES completion:nil];
}
#pragma mark - 保存请求下来的数据
-(void)saveInputDefaultValue {
    NSMutableDictionary *allValues = [[NSMutableDictionary alloc] init];
    _oldInputValues = @"";
    for (InputSectionModel *sectionModel in self.viewModel.dataModel.templates) {
        NSMutableDictionary *valuesDic = [self inputValuesWithNodes:sectionModel.nodes];
        _oldInputValues = [_oldInputValues stringByAppendingString:[ToolHelper dictionaryToJson:valuesDic]];
    }
}
#pragma mark - 判断录入信息是否已经改变 YES 改变; NO 未改变
-(BOOL)updateInputVaulesByLocal {
    if (!self.viewModel || !self.viewModel.dataModel.templates || self.viewModel.dataModel.templates.count == 0) {
        return NO;
    }
    NSString *newValues = @"";
    for (InputSectionModel *sectionModel in self.viewModel.dataModel.templates) {
        newValues = [newValues stringByAppendingString:[ToolHelper dictionaryToJson:[self inputValuesWithNodes:sectionModel.nodes]]];
    }
    if ([newValues isEqualToString:_oldInputValues]) {
        return NO;
    } else {
        return YES;
    }
}

#pragma mark - 工具方法
-(void)showHudView:(NSString *)msgStr {
    self.hudView.labelText = msgStr;
    [self.hudView show:YES];
}
-(void)hiddenHudView {
    [self.hudView hide:YES afterDelay:0.2];
}

#pragma mark - lazy
-(InputReloadView *)reloadView {
    if (!_reloadView) {
        _reloadView = [[InputReloadView alloc] init];
        _reloadView.translatesAutoresizingMaskIntoConstraints = NO;
        _reloadView.hidden = YES;
        [_reloadView.reloadBtn addTarget:self action:@selector(reloadRequest) forControlEvents:UIControlEventTouchUpInside];
    }
    return _reloadView;
}

-(InputBaseViewModel *)viewModel {
    if (!_viewModel) {
        _viewModel = [[InputBaseViewModel alloc] initWithRootViewController:self];
        __weak typeof(self)wSelf = self;
        _viewModel.showDetailViewBlock = ^(NSString *title, NSString *value) {
            [wSelf showDetailView:title value:value];
        };
    }
    return _viewModel;
}

-(InputMainListView *)mainView {
    if (!_mainView) {
        _mainView = [[InputMainListView alloc] init];
        _mainView.translatesAutoresizingMaskIntoConstraints = false;
    }
    return _mainView;
}

-(ShowDetailView *)showDetaiView {
    if (!_showDetaiView) {
        _showDetaiView = [[ShowDetailView alloc] init];
        UIWindow *window = [UIApplication sharedApplication].keyWindow;
        _showDetaiView.frame = window.frame;
    }
    return _showDetaiView;
}

-(MBProgressHUD *)hudView {
    if (!_hudView) {
        _hudView = [[MBProgressHUD alloc] initWithView:self.view];
        _hudView.color = [UIColor grayColor];
    }
    return _hudView;
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}

@end
